﻿using System;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Web.Http;
using Autofac;
using Autofac.Integration.WebApi;
using Bll;
using Common;
using CommonModel;
using Domain;
using Domain.DbContext;
using IBll;

namespace MainService
{
    /// <summary>
    /// 依赖注入配置
    /// </summary>
    public class IocConfig
    {
        /// <summary>
        /// 创建容器
        /// PS：属性为Null时候，才会去触发重新注入
        /// </summary>
        public static void BuildWebapiContainer()
        {
            #region 注册Controllers
            ContainerBuilder containerBuilder = new ContainerBuilder();
            var obj = Assembly.GetExecutingAssembly();
            containerBuilder.RegisterApiControllers(Assembly.GetExecutingAssembly()).PropertiesAutowired();//使用Autofac.WebApi2提供的RegisterApiControllers扩展方法来对程序集中所有的ApiController一次性的完成注册
            #endregion

            #region 注册实现T的类型
            Assembly[] assemblies = Directory.GetFiles(AppDomain.CurrentDomain.RelativeSearchPath, "*.dll").Select(Assembly.LoadFrom).ToArray();
            Type baseType = typeof(IDependency);
            containerBuilder.RegisterAssemblyTypes(assemblies)
                .Where(type => baseType.IsAssignableFrom(type) && !type.IsAbstract)
                .Except<ModelContainer>()//以防万一，这里直接排除这些类型的注册
                .AsSelf().AsImplementedInterfaces()
                .PropertiesAutowired();
            #endregion

            #region 补充注册（系统元数据类型,特殊处理接口的注册）

            containerBuilder.Register(a => { return DbContextUtil.GetCurrentDbContext(); }).As<ModelContainer>().PropertiesAutowired();

            #endregion

            AutofacHelper.Container = containerBuilder.Build();
            GlobalConfiguration.Configuration.DependencyResolver = new AutofacWebApiDependencyResolver(AutofacHelper.Container);//设置WebApi依赖注入解析器为Autofac提供
        }
    }
}